const mysql = require("mysql2/promise");
const { host, user, database, password } = require("../config");

const maxRetryCount = 5;
let retryCount = 0;

const pool = mysql.createPool({
	host,
	user,
	password,
	database,
	waitForConnections: true,
	connectionLimit: 10,
	queueLimit: 0
});

const connectWithRetry = async (retryInterval = 3000) => {
	try {
		const connection = await mysql.createConnection({ host, user, password, database });
		console.log("MySQL连接成功");
		// 确保连接能够正常关闭
		await connection.end();
	} catch (error) {
		console.error(`MySQL连接失败: ${error.message}`);
		if (retryCount < maxRetryCount) {
			retryCount++;
			const delay = retryInterval * Math.pow(2, retryCount); // 指数退避策略
			console.log(`等待 ${delay / 1000} 秒后进行第 ${retryCount} 次重试...`);
			setTimeout(connectWithRetry, delay, retryInterval);
		} else {
			console.error(`MySQL连接失败，已达到最大重试次数 ${maxRetryCount}`);
			// 在这里执行清理工作，例如发送通知、记录错误等
			process.exit(1);
		}
	}
};

connectWithRetry();

module.exports = pool;